package com.solution.admin.coupon.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.solution.admin.coupon.constants.CouponConstants;
import com.solution.admin.coupon.constants.CouponConstants.IsUsed;
import com.solution.admin.coupon.constants.CouponConstants.TimeType;
import com.solution.admin.coupon.dao.CouponGetRuleDao;
import com.solution.admin.coupon.entity.CouponEntity;
import com.solution.admin.coupon.entity.CouponGetEntity;
import com.solution.admin.coupon.entity.CouponGetRuleEntity;
import com.solution.admin.coupon.service.CouponGetRuleService;
import com.solution.admin.coupon.service.CouponGetService;
import com.solution.admin.coupon.service.CouponService;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus.IS_DELETE;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.constants.PublicStatus.SysCode;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;

/**
 * 优惠券信息web控制层
 * 
 * @author xu_cc
 * @date 2017-11-16 11:11:20
 */
@RequestMapping("/coupon")
@Controller
public class CouponController extends BaseController {

	@Autowired
	private CouponService couponService;
	@Autowired
	private CouponGetService couponGetService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private CouponGetRuleService couponGetRuleService;

	@Autowired
	KeyMapService keyMapService;

	/** 操作类型-修改状态 */
	static final int DO_MODIFY_STATUS = 1;
	/** 操作类型-编辑 */
	static final int DO_MODIFY = 2;
	/** 操作类型-删除 */
	static final int DO_DELETE = 3;

	/**
	 * 用于时间类型映射
	 * 
	 * @param binder
	 *            void
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月16日 下午5:50:02
	 */
	@InitBinder
	public void init(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
	}

	/**
	 * 使用优惠券
	 * 
	 * @param request
	 * @param couponId
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月17日 上午11:14:08
	 */
	@ResponseBody
	@RequestMapping("/doUseCoupon")
	public BaseReturn doUseCoupon(HttpServletRequest request, Long couponGetId, String billCode) {
		BaseReturn result = new BaseReturn();
		try {
			CouponGetEntity couponGet = couponGetService.getCouponGetById(couponGetId);
			if (IsUsed.USED.equals(couponGet.getIsUsed())) {
				result.setCode(SysCode.FAILED);
				result.setMsg("优惠券已被使用！");
				return result;
			}
			// 获取优惠券信息
			CouponEntity coupon = couponService.getCouponById(couponGet.getCouponId());
			// 状态验证、是否删除验证
			if (STATUS.DISABLED.getId().equals(coupon.getStatus())) {
				result.setCode(SysCode.FAILED);
				result.setMsg("该优惠券已暂停领取！");
				return result;
			}
			if (IS_DELETE.DELETED.getId().equals(coupon.getIsDelete())) {
				result.setCode(SysCode.FAILED);
				result.setMsg("该优惠券已作废，不可领取！");
				return result;
			}
			// 使用表
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("couponGetId", couponGetId);
			paramMap.put("isUsed", IsUsed.USED);
			List<CouponGetEntity> usedList = couponGetService.listCouponGet(paramMap);
			if (null != usedList && usedList.size() > 0) {
				throw new Exception("优惠券已经用过了！");
			}
			// 领取时间验证
			Date currentDate = new Date();
			if (!(couponGet.getBeginTime().before(currentDate) && couponGet.getEndTime().after(currentDate))) {
				result.setCode(SysCode.FAILED);
				String beginGetDateStr = DateUtils.formatDateTime(couponGet.getBeginTime());
				String endGetDateStr = DateUtils.formatDateTime(couponGet.getEndTime());
				result.setMsg("当前时间无法使用该优惠券，优惠券使用时间是[" + beginGetDateStr + " ~ " + endGetDateStr + "]！");
				return result;
			}
			// 使用优惠券
			couponService.doUseCoupon(couponGetId, getUserCode(), billCode, couponGet.getCouponId());
			result.setCode(SysCode.SUCCESS);
			result.setMsg("优惠券使用成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("优惠券使用异常，请重试！");
		}
		return result;
	}

	/**
	 * 领取优惠券
	 * 
	 * @param request
	 * @param couponId
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月17日 上午11:14:08
	 */
	@ResponseBody
	@RequestMapping("/doGetCoupon")
	public BaseReturn doGetCoupon(HttpServletRequest request, Long couponId, String userCode) {
		BaseReturn result = new BaseReturn();
		if (StringUtil.isEmpty(userCode)) {
			userCode = getUserCode();
		}
		try {
			// 获取优惠券信息
			CouponEntity coupon = couponService.getCouponById(couponId);
			if (null == coupon) {
				result.setCode(SysCode.FAILED);
				result.setMsg("优惠券领取失败，该优惠券不存在！");
				return result;
			}
			// 状态验证、是否删除验证
			if (STATUS.DISABLED.getId().equals(coupon.getStatus())) {
				result.setCode(SysCode.FAILED);
				result.setMsg("该优惠券已暂停领取！");
				return result;
			}
			if (IS_DELETE.DELETED.getId().equals(coupon.getIsDelete())) {
				result.setCode(SysCode.FAILED);
				result.setMsg("该优惠券已作废，不可领取！");
				return result;
			}
			// 领取时间验证
			Date currentDate = new Date();
			if (!(coupon.getBeginGetTime().before(currentDate) && coupon.getEndGetTime().after(currentDate))) {
				result.setCode(SysCode.FAILED);
				String beginGetDateStr = DateUtils.formatDateTime(coupon.getBeginGetTime());
				String endGetDateStr = DateUtils.formatDateTime(coupon.getEndGetTime());
				result.setMsg("当前时间无法领取该优惠券，优惠券领取时间是[" + beginGetDateStr + " ~ " + endGetDateStr + "]！");
				return result;
			}
			// 校验优惠券已领取数量
			int getNumber = couponGetService.getCouponGetCount(couponId, null);
			if (coupon.getIssueNumber() <= getNumber) {
				result.setCode(SysCode.FAILED);
				result.setMsg("该优惠券已被领完了！");
				return result;
			}
			// 每人限领(不为空，说明有限领)
			if (null != coupon.getLimitNumber()) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("couponId", couponId);
				param.put("userCode", userCode);
				// 当前人已领取该优惠券的数量
				List<CouponGetEntity> gotList = couponGetService.listCouponGet(param);
				int gotCount = (null != gotList) ? gotList.size() : 0;
				if (gotCount >= coupon.getLimitNumber()) {
					result.setCode(SysCode.FAILED);
					result.setMsg("您已领取 " + gotCount + " 张了，机会留给别人吧！");
					return result;
				}
			}
			// 执行优惠券领取操作
			CouponGetEntity couponGetEntity = new CouponGetEntity();
			couponGetEntity.setCouponId(couponId);
			couponGetEntity.setCreater(getUserName());
			couponGetEntity.setCustomerId(getCustomerId());
			couponGetEntity.setIsUsed(IsUsed.UN_USED);
			// 设置优惠券有效期
			if (TimeType.TIME_START_STOP.equals(coupon.getTimeType())) {
				// 起止时间
				couponGetEntity.setBeginTime(coupon.getBeginTime());
				couponGetEntity.setEndTime(coupon.getEndTime());
			} else if (TimeType.TIME_DAYS.equals(coupon.getTimeType())) {
				// 天数，计算
				couponGetEntity.setBeginTime(currentDate);
				Calendar ca = Calendar.getInstance();
				ca.add(Calendar.DATE, coupon.getLimitDay());
				Date endTime = ca.getTime();
				couponGetEntity.setEndTime(endTime);
			}
			couponGetService.saveCouponGet(couponGetEntity);
			result.setCode(SysCode.SUCCESS);
			result.setMsg("优惠券领取成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("优惠券领取异常，请重试！");
		}
		return result;
	}

	/**
	 * 获取优惠券领用数量
	 * 
	 * @param request
	 * @param couponId
	 * @return int
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月16日 下午5:12:47
	 */
	@ResponseBody
	@RequestMapping("/getCouponGetCount")
	public int getCouponGetCount(HttpServletRequest request, Long couponId) {
		try {
			return couponGetService.getCouponGetCount(couponId, null);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 获取优惠券使用数量
	 * 
	 * @param request
	 * @param couponId
	 * @return int
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月16日 下午5:12:47
	 */
	@ResponseBody
	@RequestMapping("/getCouponUsedCount")
	public int getCouponUsedCount(HttpServletRequest request, Long couponId) {
		try {
			return couponGetService.getCouponGetCount(couponId, IsUsed.USED);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 跳转优惠券信息查询页面
	 * 
	 * @param Coupon
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-11-16 11:11:20
	 */
	@RequestMapping("/toListCouponPage")
	public String toListCouponPage(CouponEntity coupon, HttpServletRequest request, Model model) {
		model.addAttribute("systemTime", System.currentTimeMillis());
		return "coupon/coupon_list";
	}

	/**
	 * 分页查询优惠券信息列表
	 * 
	 * @param coupon
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-11-16 11:11:20
	 */
	@RequestMapping("/listCouponPage")
	@ResponseBody
	public JSONGrid listCouponPage(CouponEntity coupon, HttpServletRequest request, String couponDate, String couponGetDate) {
		try {
			int pageNum = Integer.parseInt(request.getParameter("page").toString());
			int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
			PageParam pageParam = super.getPageParam(request);
			pageParam.setPageNum(pageNum);
			pageParam.setNumPerPage(numPerPage);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("status", coupon.getStatus());
			paramMap.put("couponName", coupon.getCouponName());
			// 领取时间
			if (StringUtil.isNotNull(couponGetDate) && couponGetDate.indexOf(" - ") > 0) {
				String[] couponGetDateArr = couponGetDate.split(" - ");
				Date beginTime = DateUtils.parseDate(couponGetDateArr[0]);
				Date endTime = DateUtils.parseDate(couponGetDateArr[1]);
				paramMap.put("beginGetTime", beginTime);
				paramMap.put("endGetTime", endTime);
			}
			// 使用时间
			if (StringUtil.isNotNull(couponDate) && couponDate.indexOf(" - ") > 0) {
				String[] couponDateArr = couponDate.split(" - ");
				Date beginTime = DateUtils.parseDate(couponDateArr[0]);
				Date endTime = DateUtils.parseDate(couponDateArr[1]);
				paramMap.put("beginTime", beginTime);
				paramMap.put("endTime", endTime);
			}
			PageBean pageBean = couponService.listCouponPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONGrid();
	}

	/**
	 * 跳转新增页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-11-16 11:11:20
	 */
	@RequestMapping("/toAddCoupon")
	public String toAddCoupon(HttpServletRequest request, Model model) {
		// 红包期限类型
		List<KeyMapEntity> typeList = keyMapService.listKeyMap("timeType");
		model.addAttribute("timeTypeList", typeList);
		// 红包类型  01 推送红包  02 - 登录红包 
		List<KeyMapEntity> couponTypeList = keyMapService.listKeyMap("couponType");
		model.addAttribute("couponTypeList", couponTypeList);
		// 红包停用类型  01 - 指定客户  02 - 指定客户等级  03- 指定客户区域  04 指定客户业务员 05 -所有  
		List<KeyMapEntity> getTargetTypeList = keyMapService.listKeyMap("getTargetType");
		model.addAttribute("getTargetTypeList", getTargetTypeList);
		// 红包 使用类型  01 - 指定商品  02 - 指定商品类型  03- 指定品牌 04 - 所有商品
		List<KeyMapEntity> useTargetTypeList = keyMapService.listKeyMap("useTargetType");
		model.addAttribute("useTargetTypeList", useTargetTypeList);
		return "coupon/coupon_form";
	}

	/**
	 * 跳转编辑页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-11-16 11:11:20
	 */
	@RequestMapping("/toUpdateCoupon")
	public String toUpdateCoupon(HttpServletRequest request, Model model) {
		// 编辑操作
		long id = Long.valueOf(request.getParameter("id"));
		try {
			// 红包期限类型
			List<KeyMapEntity> typeList = keyMapService.listKeyMap("timeType");
			model.addAttribute("timeTypeList", typeList);
			// 红包类型  01 推送红包  02 - 登录红包 
			List<KeyMapEntity> couponTypeList = keyMapService.listKeyMap("couponType");
			model.addAttribute("couponTypeList", couponTypeList);
			// 红包停用类型  01 - 指定客户  02 - 指定客户等级  03- 指定客户区域  04 指定客户业务员 05 -所有  
			List<KeyMapEntity> getTargetTypeList = keyMapService.listKeyMap("getTargetType");
			model.addAttribute("getTargetTypeList", getTargetTypeList);
			// 红包 使用类型  01 - 指定商品  02 - 指定商品类型  03- 指定品牌 04 - 所有商品
			List<KeyMapEntity> useTargetTypeList = keyMapService.listKeyMap("useTargetType");
			model.addAttribute("useTargetTypeList", useTargetTypeList);
			
			CouponEntity coupon = couponService.getCouponById(id);
			model.addAttribute("coupon", coupon);
			
			// 查询红包领取、使用限制数据
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("couponId", coupon.getId());
			List<CouponGetRuleEntity> ruleList = couponGetRuleService.listCouponGetRule(param);
			List<CouponGetRuleEntity> getTargetList = new ArrayList<CouponGetRuleEntity>();
			List<CouponGetRuleEntity> useTargetList = new ArrayList<CouponGetRuleEntity>();
			if(ruleList != null){
				for (CouponGetRuleEntity rule : useTargetList) {
					if(CouponConstants.COUPON_TARGET_TYPE.GET.getCode().equals(rule.getTargetType())){
						getTargetList.add(rule);
					}else if(CouponConstants.COUPON_TARGET_TYPE.USE.getCode().equals(rule.getTargetType())){
						useTargetList.add(rule);
					}
				}
			}
			model.addAttribute("getTargetList", getTargetList);
			model.addAttribute("useTargetList", useTargetList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "coupon/coupon_form";
	}

	/**
	 * 跳转详情页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-11-16 11:11:20
	 */
	@RequestMapping("/toDetail")
	public String toDetail(HttpServletRequest request, Model model) {
		// 编辑操作
		long id = Long.valueOf(request.getParameter("id"));
		try {
			// String couponDate,
			// String couponGetDate
			List<KeyMapEntity> typeList = keyMapService.listKeyMap("timeType");
			model.addAttribute("timeTypeList", typeList);
			CouponEntity coupon = couponService.getCouponById(id);
			model.addAttribute("coupon", coupon);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "coupon/coupon_view";
	}

	/**
	 * 删除优惠券
	 * 
	 * @Title: doDelPromotion
	 * @Description:(描述)
	 * @param request
	 * @param id
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月11日 下午8:12:34
	 */
	@RequestMapping("/doDelCoupon")
	@ResponseBody
	public BaseReturn doDelPromotion(HttpServletRequest request, Long id) {
		BaseReturn result = new BaseReturn();
		try {
			if (checkTimeStatus(id, DO_DELETE)) {
				int getNumber = couponGetService.getCouponGetCount(id, null);
				if (getNumber > 0) {
					result.setCode(SysCode.FAILED);
					result.setMsg("已有人领取该优惠券，不可删除，作废可停用！");
				} else {
					int rows = couponService.deleteCouponById(id);
					if (rows > 0) {
						result.setCode(SysCode.SUCCESS);
						result.setMsg("优惠券删除成功！");
					} else {
						result.setCode(SysCode.FAILED);
						result.setMsg("优惠券删除失败！");
					}
				}
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("仅允许删除未开始的优惠券，请刷新重试！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("优惠券删除异常！");
		}
		return result;
	}

	/**
	 * 新增或保存优惠券信息
	 * 
	 * @param request
	 *            请求对象
	 * @param couponEntity
	 *            优惠券信息实体
	 * @return
	 * @author xu_cc
	 * @date 2017-11-16 11:11:20
	 */
	@RequestMapping("/saveCoupon")
	@ResponseBody
	public BaseReturn saveCoupon(HttpServletRequest request, CouponEntity couponEntity, String couponDate, String couponGetDate) {
		BaseReturn result = new BaseReturn();
		try {
			if (null == couponEntity) {
				result.setCode(SysCode.FAILED);
				result.setMsg("优惠券信息保存失败！");
				return result;
			}
			// 优惠券领取起止时间
			if (StringUtil.isEmpty(couponGetDate)) {
				result.setCode(SysCode.FAILED);
				result.setMsg("优惠券信息保存失败，请选择优惠券领取起止时间！");
				return result;
			} else {
				// 优惠券有效期起止时间
				String[] couponGetDateArr = couponGetDate.split(" - ");
				Date startDate = DateUtils.parseDate(couponGetDateArr[0]);
				Date endDate = DateUtils.parseDate(couponGetDateArr[1]);
				couponEntity.setBeginGetTime(startDate);
				couponEntity.setEndGetTime(endDate);
			}
			// 优惠券 有效期
			if (TimeType.TIME_START_STOP.equals(couponEntity.getTimeType())) {
				if (StringUtil.isEmpty(couponDate)) {
					result.setCode(SysCode.FAILED);
					result.setMsg("优惠券信息保存失败，请选择优惠券有效期起止时间！");
					return result;
				} else {
					// 优惠券有效期起止时间
					String[] couponDateArr = couponDate.split(" - ");
					Date startDate = DateUtils.parseDate(couponDateArr[0]);
					Date endDate = DateUtils.parseDate(couponDateArr[1]);
					couponEntity.setBeginTime(startDate);
					couponEntity.setEndTime(endDate);
				}
				// 在选择起止时间的基础上，优惠券的使用时间必须晚于领取时间
				// !(couponEntity.getBeginTime().getTime() >
				// couponEntity.getBeginGetTime().getTime())
				// && (couponEntity.getEndTime().getTime() >
				// couponEntity.getEndGetTime().getTime())
				if (couponEntity.getBeginTime().before(couponEntity.getBeginGetTime())
				        || couponEntity.getEndTime().before(couponEntity.getEndGetTime())) {
					result.setCode(SysCode.FAILED);
					result.setMsg("优惠券使用时间必须晚于领取时间！");
					return result;
				}
			} else if (TimeType.TIME_DAYS.equals(couponEntity.getTimeType())) {
				if (null == couponEntity.getLimitDay()) {
					result.setCode(SysCode.FAILED);
					result.setMsg("优惠券信息保存失败，请输入有效期天数！");
					return result;
				}
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("优惠券信息保存失败，请选择优惠券期限类型！");
				return result;
			}
			couponEntity.setModifier(getUserName());
			// 领用类型
			String getTargetType = request.getParameter("getTargetType");
			String getTargetList = request.getParameter("getTargetList");
			couponEntity.setGetTargetType(getTargetType);
			couponEntity.setGetTargetList(getTargetList);
			// 使用类型
			String useTargetType = request.getParameter("useTargetType");
			String useTargetList = request.getParameter("useTargetList");
			couponEntity.setUseTargetType(useTargetType);
			couponEntity.setUseTargetList(useTargetList);
			
			String id = request.getParameter("id");
			if (StringUtil.isNotEmpty(id)) {
				couponService.updateCoupon(couponEntity);
			} else {
				// 待审核
				couponEntity.setApproveStatus(CouponConstants.COUPON_APPROVE_STATUS.TO_APPROVE.getCode());
				couponEntity.setCreater(getUserName());
				couponEntity.setIsDelete(IS_DELETE.NORMAL.getId());
				couponEntity.setStatus(STATUS.ENABLED.getId());
				couponService.saveCoupon(couponEntity);
			}
			result.setCode(com.solution.common.constants.PublicStatus.SysCode.SUCCESS);
			result.setMsg("优惠券信息保存成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(com.solution.common.constants.PublicStatus.SysCode.ERROR);
			result.setMsg("优惠券信息保存异常！");
		}
		return result;
	}

	/**
	 * 修改优惠券状态
	 * 
	 * @param request
	 * @param id
	 * @param status
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月11日 下午8:23:02
	 */
	@RequestMapping("/updateStatus")
	@ResponseBody
	public BaseReturn updateStatus(HttpServletRequest request, Long id, String status) {
		BaseReturn result = new BaseReturn();
		try {
			if (checkTimeStatus(id, DO_MODIFY_STATUS)) {
				CouponEntity coupon = new CouponEntity();
				coupon.setId(id);
				coupon.setStatus(Integer.parseInt(status));
				coupon.setModifier(getUserName());
				int rows = couponService.updateCoupon(coupon);
				if (rows > 0) {
					result.setCode(SysCode.SUCCESS);
					result.setMsg("状态修改成功！");
				} else {
					result.setCode(SysCode.FAILED);
					result.setMsg("状态修改失败！");
				}
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("状态不允许修改！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("状态更新异常！");
		}
		return result;
	}

	/**
	 * 跳转至优惠券发放页面
	 * 
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月18日 下午2:41:07
	 */
	@RequestMapping("/toProvidCoupon")
	public String toProvidCoupon(HttpServletRequest request) {
		long id = Long.valueOf(request.getParameter("id"));
		try {
			CouponEntity counpon = couponService.getCouponById(id);
			request.setAttribute("counpon", counpon);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "coupon/providCoupon_form";
	}

	/**
	 * 查询优惠券发放用户列表
	 * 
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月18日 下午4:46:04
	 */
	@RequestMapping("/listCouponProvidUser")
	@ResponseBody
	public JSONGrid listCouponProvidUser(HttpServletRequest request) {
		long id = Long.valueOf(request.getParameter("id"));
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("couponId", id);
			PageBean providUserPage = couponGetService.listCouponGetPage(pageParam, paramMap);
			return new JSONGrid(providUserPage.getRecordList(), providUserPage.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONGrid();
	}

	/**
	 * 跳转至发放优惠券用户列表
	 * 
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月21日 下午5:41:17
	 */
	@RequestMapping("/toListCouponCustomer")
	public String toListCouponCustomer(HttpServletRequest request) {
		String couponId = request.getParameter("couponId");
		request.setAttribute("couponId", couponId);
		return "coupon/couponCustomer_selector";
	}

	/**
	 * 查询待发放优惠券用户
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月21日 下午3:09:15
	 */
	@RequestMapping("/listCouponCustomer")
	@ResponseBody
	public JSONGrid listCustomer(HttpServletRequest request) {
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		String couponId = request.getParameter("couponId");
		String customerLevel = request.getParameter("customerLevel");
		List<String> customerLevelArray = new ArrayList<String>();
		if (null != customerLevel && !"".equals(customerLevel)) {
			customerLevelArray = Lists.newArrayList(customerLevel.split(","));
		}
		try {
			CouponEntity coupon = couponService.getCouponById(Long.parseLong(couponId));
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("couponId", couponId);
			paramMap.put("mobile", request.getParameter("mobile"));
			paramMap.put("companyName", request.getParameter("companyName"));
//			paramMap.put("getNum", request.getParameter("getNum"));
			paramMap.put("customerName", request.getParameter("customerName"));
			paramMap.put("limitNumber", coupon.getLimitNumber());
			paramMap.put("customerLevelArray", customerLevelArray);
			paramMap.put("provinceCode", request.getParameter("provinceCode"));
			paramMap.put("cityCode", request.getParameter("cityCode"));
			paramMap.put("areaCode", request.getParameter("areaCode"));
			PageBean customerPage = couponService.listCouponCustomerPage(pageParam, paramMap);
			return new JSONGrid(customerPage.getRecordList(), customerPage.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONGrid();
	}

	/**
	 * 查询所有待发放用户
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月21日 下午3:09:15
	 */
	@RequestMapping("/listCouponCustomerAll")
	@ResponseBody
	public Map<String, Object> listCustomerAll(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		String couponId = request.getParameter("couponId");
		String customerLevel = request.getParameter("customerLevel");
		List<String> customerLevelArray = new ArrayList<String>();
		if (null != customerLevel && !"".equals(customerLevel)) {
			customerLevelArray = Lists.newArrayList(customerLevel.split(","));
		}
		try {
			CouponEntity coupon = couponService.getCouponById(Long.parseLong(couponId));
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("couponId", couponId);
			paramMap.put("mobile", request.getParameter("mobile"));
//			paramMap.put("getNum", request.getParameter("getNum"));
			paramMap.put("customerName", request.getParameter("customerName"));
			paramMap.put("limitNumber", coupon.getLimitNumber());
			paramMap.put("customerLevelArray", customerLevelArray);
			paramMap.put("provinceCode", request.getParameter("provinceCode"));
			paramMap.put("cityCode", request.getParameter("cityCode"));
			paramMap.put("areaCode", request.getParameter("areaCode"));
			List<Map<String,Object>> customerListMap = couponService.listCouponCustomer( paramMap);
			
			result.put("code", SysCode.SUCCESS);
			result.put("msg", "查询成功");
			result.put("data", customerListMap);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", SysCode.FAILED);
			result.put("msg", "添加失败");
		}
		return result;
	}

	/**
	 * 发放优惠券
	 * 
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月23日 下午4:43:28
	 */
	@RequestMapping("/providCoupon")
	@ResponseBody
	public BaseReturn providCoupon(HttpServletRequest request) {
		BaseReturn result = new BaseReturn();
		long id = Long.parseLong(request.getParameter("id"));
		String timeType = request.getParameter("timeType");
		Integer sendTotalNum = Integer.parseInt(request.getParameter("sendTotalNum"));
//		List<Long> customerIdList = JSONArray.parseArray(request.getParameter("customerIdArr"), Long.class);
		JSONArray array = JSONArray.parseArray(request.getParameter("customerSendArr"));
		try {
			CouponEntity coupon = couponService.getCouponById(id);
			// 校验优惠券已领取数量
			int getNumber = couponGetService.getCouponGetCount(id, null);
			if (coupon.getIssueNumber() <= getNumber) {
				result.setCode(SysCode.FAILED);
				result.setMsg("该优惠券已被领完了！");
				return result;
			}
//			// 超量发放(发放数量 < 已领数量 + (用户人数 * 限领数量))
//			if (coupon.getIssueNumber() < (getNumber + (array.size() * coupon.getLimitNumber()))) {
			// 超量发放(发放数量 < 已领数量 + 本次发放总数)
			if (coupon.getIssueNumber() < (getNumber + sendTotalNum)) {
				result.setCode(SysCode.FAILED);
				result.setMsg("发放数超过允许数量！");
				return result;
			}
			List<CouponGetEntity> couponGetList = new ArrayList<CouponGetEntity>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject customerSendObject = array.getJSONObject(i);
				//按填写发放数量领取
				for (int j = 0; j < customerSendObject.getIntValue("sendNum"); j++) {
					CouponGetEntity couponGet = new CouponGetEntity();
					couponGet.setCouponId(coupon.getId());
					couponGet.setCustomerId(customerSendObject.getLong("customerId"));
					
					// 设置优惠券有效期
					if (TimeType.TIME_START_STOP.equals(coupon.getTimeType())) {
						// 期限
						couponGet.setBeginTime(coupon.getBeginTime());
						couponGet.setEndTime(coupon.getEndTime());
					} else if (TimeType.TIME_DAYS.equals(coupon.getTimeType())) {
						if (null == coupon.getLimitDay()) {
							result.setCode(SysCode.FAILED);
							result.setMsg("优惠券发放失败，该优惠券时长错误！");
							return result;
						}
						// 天数，计算
						couponGet.setBeginTime(new Date());
						Calendar ca = Calendar.getInstance();
						ca.add(Calendar.DATE, coupon.getLimitDay());
						Date endTime = ca.getTime();
						couponGet.setEndTime(endTime);
					} else {
						result.setCode(SysCode.FAILED);
						result.setMsg("优惠券发放失败，优惠券类型错误！");
						return result;
					}
					couponGet.setIsUsed(IsUsed.UN_USED);
					couponGetList.add(couponGet);
				}
			}
			couponGetService.saveCouponGet(couponGetList);
			result.setCode(SysCode.SUCCESS);
			result.setMsg("优惠券发放成功！");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.FAILED);
			result.setMsg("优惠券发放异常！");
		}
		return result;
	}

	/**
	 * 比较系统时间，判断活动可否修改
	 * 
	 * @Title: checkTimeStatus
	 * @Description:(描述)
	 * @param promotionId
	 * @param handleType
	 * @return boolean
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月12日 上午11:20:23
	 */
	private boolean checkTimeStatus(Long couponId, int handleType) {
		try {
			Date currentDate = new Date();
			CouponEntity coupon = couponService.getCouponById(couponId);
			if (TimeType.TIME_START_STOP.equals(coupon.getTimeType())) {
				// 有效期起止时间
				// 未开始状态下，可以进行所有操作,开始时间晚于当前系统时间
				if (coupon.getBeginTime().after(currentDate)) {
					return true;
				} else {
					// 进行中，或者已结束，使其只能修改启用停用状态
					if (DO_MODIFY_STATUS == handleType) {
						return true;
					} else {
						return false;
					}
				}
			} else if (TimeType.TIME_DAYS.equals(coupon.getTimeType())) {
				// 时长，根据领取时间判断
				// 未开始状态下，可以进行所有操作,开始时间晚于当前系统时间
				if (coupon.getBeginGetTime().after(currentDate)) {
					return true;
				} else {
					// 进行中，或者已结束，使其只能修改启用停用状态
					if (DO_MODIFY_STATUS == handleType) {
						return true;
					} else {
						return false;
					}
				}
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
